﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DinhMuc.BUL;
using DinhMuc.Public;
using DinhMuc.UI.Frm_Form;
using Janus.Windows.GridEX;
using System.Data.OleDb;
using iTextSharp.text.pdf;
using iTextSharp.text;
using Janus.Windows.Schedule;
namespace DinhMuc.UI.Form_bang
{
    public partial class frm_QLDonHang : UserControl
    {
        public frm_QLDonHang()
        {
            InitializeComponent();
        }
        tblQLDonHangBUL qldh = new tblQLDonHangBUL();
        DataTable dtOutput = new DataTable("table");
        private void frm_QLDonHang_Load(object sender, EventArgs e)
        {
             //tblPhanQuyenBUL p = new tblPhanQuyenBUL();
            //int exe = p.xetPhanQuyenTrongForm(Form1.maQuanLy, this.Name, btnTim, btnAn, btnExcel, btnPrint);
            loadToComBoBox_tienDo();
            gridEX2.RootTable.AllowAddNew = Janus.Windows.GridEX.InheritableBoolean.False;
            //for (int i = 0; i < 11; i++)
            //{
            //    gridEX2.RootTable.Columns[i].EditType = Janus.Windows.GridEX.EditType.NoEdit;
            //}
        }

        private void gridEX1_FormattingRow(object sender, Janus.Windows.GridEX.RowLoadEventArgs e)
        {

        }

        private void btnLoc_Click(object sender, EventArgs e)
        {
            tblQLDonHangPublic p = new tblQLDonHangPublic(
               dateTu.Value,
               dateDen.Value
               );
            dtOutput=qldh.locNgayLap(p);
            gridEX2.DataSource = dtOutput;
        }


        private void button2_Click(object sender, EventArgs e)
        {
            Janus.Windows.GridEX.GridEXPrintDocument print = new Janus.Windows.GridEX.GridEXPrintDocument();
            PrintPreviewDialog printView = new PrintPreviewDialog();
            
            printView.Document = print;
            printView.ShowDialog();
            print.Print();
        }

        private void gridEX1_RecordUpdated(object sender, EventArgs e)
        {
            int soDH = int.Parse(gridEX2.GetValue("soDH").ToString());
            string tienDo = gridEX2.GetValue("ketQua").ToString();
            tblQLDonHangPublic p = new tblQLDonHangPublic(soDH,tienDo);
            qldh.suaTienDo(p);
        }
        private void loadToComBoBox_tienDo()
        {
            DataTable dt = qldh.loadToComBoBox_tienDo();
            gridEX2.DropDowns["comBoBox_tienDo"].DataSource = dt;
        }

        private void btnthemMoi_Click(object sender, EventArgs e)
        {
            frm_themMoiDongHang frm = new frm_themMoiDongHang();
            frm.ShowDialog();
            frm_QLDonHang_Load(sender, e);
        }

        private void gridEX2_FormattingRow(object sender, Janus.Windows.GridEX.RowLoadEventArgs e)
        {
            if (e.Row.RowType == RowType.Record) // dien kien chi to mau dong co du lieu, "record" 
            {
                //mau xanh
                GridEXFormatStyle xanh = new GridEXFormatStyle();
                xanh.BackColor = System.Drawing.Color.Green;
                //maudo
                GridEXFormatStyle maudo = new GridEXFormatStyle();
                maudo.BackColor = System.Drawing.Color.Red;
                //mau tim
                GridEXFormatStyle tim = new GridEXFormatStyle();
                tim.BackColor = System.Drawing.Color.Fuchsia;
                string value = e.Row.Cells["ketQua"].Value.ToString();
                if (value == "xong")
                    e.Row.RowStyle = xanh;
                if (value == "huy")
                    e.Row.RowStyle = maudo;
                if (value == "chua")
                    e.Row.RowStyle = tim;

            }
        }

        private void imPort_Click(object sender, EventArgs e)
        {
             tblDonHangBUL bul = new tblDonHangBUL();
            OpenFileDialog file = new OpenFileDialog();
            if (file.ShowDialog() == DialogResult.OK)
            {
                OleDbConnection connect = new OleDbConnection();
                connect.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file.FileName + ";Extended Properties=Excel 4.0";
                if (connect.State == ConnectionState.Closed)
                    connect.Open();
                OleDbCommand command = new OleDbCommand("select * from [sheet1$]", connect);
                OleDbDataAdapter adapter = new OleDbDataAdapter(command);
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    tblDonHangPuclic p = new tblDonHangPuclic();
                    p.soDH = int.Parse("0" + row[0].ToString());
                    p.maSP = row[1].ToString();
                    p.maKH = row[2].ToString();
                    p.maTrucIn = row[3].ToString();
                    p.ngayLap = Convert.ToDateTime(row[4].ToString());
                    p.nguoiPhuTrach = row[5].ToString();
                    p.DVT = row[6].ToString();
                    p.slDonHang = int.Parse("0" + row[7].ToString());
                    p.tgGiaoHang = Convert.ToDateTime(row[8].ToString());
                    p.khoMang = int.Parse("0" +row[9].ToString());
                    p.DoDay = float.Parse("0"+row[10].ToString());
                    p.ghiChu = row[11].ToString();
                    p.ketQua = row[12].ToString();
                    bul.import("insert into qldonhang(sodh,masp,makh,matrucin,ngayLap,nguoiPhuTrach,DVT,slDonHang,tgGiaoHang,khoMang,doDay,ghiChu,ketQua)values(@A,@B,@C,@D,@E,@F,@G,@H,@I,@J,@K,@L,@M)", p);

                }
                MessageBox.Show("Import Dữ Liệu Thành Công");
            }
        }
        //excel
        private void button1_Click(object sender, EventArgs e)
        {
            this.saveFileDialog1.Filter = "txt files (*.xls)|*.xls|All files (*.*)|*.*";
            if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = this.saveFileDialog1.FileName;
                FileStream stream = new FileStream(fileName.Trim(), FileMode.Create);
                this.gridEXExporter1.Export(stream);
                stream.Close();
                MessageBox.Show("Xuất thành công!");
            }
        }
        //word
        private void button2_Click_1(object sender, EventArgs e)
        {
            this.saveFileDialog1.Filter = "txt files (*.doc)|*.docx|All files (*.*)|*.*";
            if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = this.saveFileDialog1.FileName;
                Export2Word(dtOutput);
                MessageBox.Show("Xuất thành công!");
            }
        }
        //pdf
        private void button1_Click_1(object sender, EventArgs e)
        {
            this.saveFileDialog1.Filter = "txt files (*.pdf)|*.fdf|All files (*.*)|*.*";
            if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = this.saveFileDialog1.FileName;
                ExportToPdf(dtOutput,saveFileDialog1.FileName);
                MessageBox.Show("Xuất thành công!");
            }
        }
        void Export2Word(DataTable datatable1)
        {
            //Tạo các đối tượng application, document, table của MS Word
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document doc;
            Microsoft.Office.Interop.Word.Table table;

            //Hiện (mở) ứng dụng word
            app.Visible = true;

            //Tham số truyền vào các hàm có đối là tuỳ chọn
            object obj = Type.Missing;

            //Tạo một tài liệu mới (để chứa dữ liệu xuất ra)
            doc = app.Documents.Add(ref obj, ref obj, ref obj, ref obj);

            Microsoft.Office.Interop.Word.Range range = doc.Range(ref obj, ref obj);

            //Thêm một bảng có 2 cột và số hàng bằng với số hàng trong datatable.
            table = doc.Tables.Add(range, datatable1.Rows.Count, datatable1.Columns.Count, ref obj, ref obj);

            //Xuất dữ liệu từ datatable sang bảng (trong word). Chú ý: đối với các đối tượng tập hợp
            // trong word thì phần tử đầu tiên có chỉ số là 1 thay vì 0 như trong C#
            for (int i = 0; i < datatable1.Rows.Count; i++)
            {
                for (int j = 0; j < datatable1.Columns.Count; j++)
                {
                    doc.Tables[1].Rows[i + 1].Cells[j + 1].Range.Text = datatable1.Rows[i][j].ToString();
                }
                //doc.Tables[1].Rows[i + 1].Cells[1].Range.Text = datatable1.Rows[i]["STT"].ToString();
                //doc.Tables[1].Rows[i + 1].Cells[2].Range.Text = datatable1.Rows[i]["HoTen"].ToString();
            }
            //Thêm đường viền cho Table nếu cần.
            doc.Select();
            Microsoft.Office.Interop.Word.WdLineStyle BorderValue = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            app.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle = BorderValue;
            app.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = BorderValue;
            app.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineStyle = BorderValue;
            app.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineStyle = BorderValue;
            app.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].LineStyle = BorderValue;
            app.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].LineStyle = BorderValue;
        }
        public void ExportToPdf(DataTable dt, string path)
        {
            iTextSharp.text.Document document = new iTextSharp.text.Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
            document.Open();
            iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);

            PdfPTable table = new PdfPTable(dt.Columns.Count);
            PdfPRow row = null;
            //float[] widths = new float[4];
            //widths[0] = 4F;
            //widths[1] = 4F;
            //widths[2] = 4F;
            //widths[3] = 4F; 

            //table.SetWidths(widths);

            table.WidthPercentage = 100;
            int iCol = 0;
            string colname = "";
            PdfPCell cell = new PdfPCell(new Phrase("Products"));

            cell.Colspan = dt.Columns.Count;

            foreach (DataColumn c in dt.Columns)
            {

                table.AddCell(new Phrase(c.ColumnName, font5));
            }

            foreach (DataRow r in dt.Rows)
            {
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        table.AddCell(new Phrase(r[i].ToString(), font5));
                    }
                    //table.AddCell(new Phrase(r[2].ToString(), font5));
                    //table.AddCell(new Phrase(r[3].ToString(), font5));
                }
            } document.Add(table);
            document.Close();
        }

        //In 
        private void button3_Click(object sender, EventArgs e)
        {
            GridEXPrintDocument print = new GridEXPrintDocument();
            PrintPreviewDialog PrintPreviewDialog1 = new PrintPreviewDialog();
            
            PrintPreviewDialog1.Document = print;
            print.DefaultPageSettings.Landscape = true;
            print.GridEX = this.gridEX2;
            print.ExpandFarColumn = true;
            PrintPreviewDialog1.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
            PrintPreviewDialog1.ShowDialog();


        }
            
    }
}
